package org.database.listener;

import com.mybatisflex.core.datasource.FlexDataSource;
import org.database.attribute.CustomDataSourceAttribute;
import org.database.config.CustomDataSourceConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Map;

/**
 * DataSourceInitListener
 *
 * @author grl
 * @date 2024/2/2
 */
@Component
@ConditionalOnProperty(value = "database.sharding.enable",havingValue = "true")
public class DataSourceInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${database.sharding.dataSourceName:sharding-db}")
    private String shardingDataSourceName;

    @Autowired
    private CustomDataSourceAttribute properties;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        /**
         *  使用 ShardingJDBC 时 会导致多数据源切换失效，只注入了sharding 的数据源，将其他数据源动态加入到flexDataSource中
         *  使数据源动态切换数据源功能正常
         *  如需要切换到动态增加的flex配置中没有的数据源必须使用 DataSourceKey.use("db2")
         *  @UseDataSource(value = "db2") 注解形式失效
         *  此时默认数据源为 shardingJDBC的数据源 key 名为  DataSourceKey.use("MyBatis-Flex")
         *  ShardingJDBC 数据源获取
         *  Map<String, DataSource> dataSourceMap = DataSourceMapSetter.getDataSourceMap(environment)
         *  mybatis Flex 数据源获取
         *  FlexDataSource flexDataSource = FlexGlobalConfig.getDefaultConfig().getDataSource()
         */
        CustomDataSourceConfiguration customDataSource = new CustomDataSourceConfiguration(properties,shardingDataSourceName);
        customDataSource.createDataSource();
    }
}
